import 'dart:collection';
import 'dart:convert' as convert;
import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/sms_bean.dart';
import 'package:app/src/http/sign.dart';
import 'package:app/src/http/url.dart';
import 'package:app/src/ui/dialog/dailog.dart';

///手机验证码
class SmsModel {
  static final String URL = "http://112.35.1.155:1992"; //http地址
  static final String ecName = "浙江亮鲸网络科技有限公司"; //企业名称
  static final String apId = "lianji"; //接口账号用户名
  static final String sign =
      "ngE5EvFes"; //签名编码。在云MAS平台『管理』→『接口管理』→『短信接入用户管理』获取。
  static final String addSerial =
      "106509712042733"; //扩展码。依据申请开户的服务代码匹配类型而定，如为精确匹配，此项填写空字符串（""）；如为模糊匹配，此项可填写空字符串或自定义的扩展码，注：服务代码加扩展码总长度不能超过20位。
  static final String secretKey = "passwd@1290N"; //密码
  //验证码模板：你好，你本次的验证码是{[验证码:纯数字，总长度10]}。
  static var templateId = "9fa2e2f1a84a4e10aa5f5d1b483755f0"; //模板id

  ///参数校验序列，生成方法：将ecName、apId、secretKey、templateId、mobiles、params、sign、addSerial按序拼接（无间隔符），通过MD5（32位小写）计算出的值
  static String _getMacWithTmpsubmit(
      String mobiles, String templateId, String params) {
    var str = ecName +
        apId +
        secretKey +
        templateId +
        mobiles +
        params.toString() +
        sign +
        addSerial;
    //dart:  浙江亮鲸网络科技有限公司lianjipasswd@1290N9fa2e2f1a84a4e10aa5f5d1b483755f015317068357[798023]ngE5EvFes106509712042733
    //kotlin 浙江亮鲸网络科技有限公司lianjipasswd@1290N9fa2e2f1a84a4e10aa5f5d1b483755f015317068357[123456]ngE5EvFes106509712042733
    //print("mac:$str");
    //mac:浙江亮鲸网络科技有限公司lianjipasswd@1290N9fa2e2f1a84a4e10aa5f5d1b483755f015317068357[861987]ngE5EvFes106509712042733
    //mac:浙江亮鲸网络科技有限公司lianjipasswd@1290N9fa2e2f1a84a4e10aa5f5d1b483755f015317068357[668266]ngE5EvFes106509712042733
    var mac = toMd5WithStr(str).toLowerCase();
    //print("mac:$mac");
    //bc254cc28af2811b4ae1e919cf21e301
    return mac;
  }

  ///获取验证码
  ///mobiles 手机号
  ///param 验证码;fixme 注意验证码首个数字最好不要为0；如：008537 最后移动那边可能会变成8537
  static void getSmsCode(BuildContext context, String mobiles, String param,
      bool isEnableLoad, ResponseCallbackWithT<SmsResult>? callback) {
    var url = URL + "/sms/tmpsubmit";
    var map = HashMap<String, dynamic>();
    map["ecName"] = ecName;
    map["apId"] = apId;
    map["mobiles"] = mobiles;
    map["sign"] = sign;
    map["addSerial"] = addSerial;
    map["templateId"] = templateId;
    //var templateId = "c81c8ced4e0844a797e84858e5fdaf92"//模板id
    //验证码模板：你好，你本次的验证码是{[验证码:纯数字，总长度10]}。
    // List<String> params=[];
    // params.add(param);
    // map["params"]=params;
    //fixme params 格式为："[123456]"；不是 ["123456"];亲测！
    var params = "[$param]";
    map["params"] = params;
    map["mac"] = _getMacWithTmpsubmit(
        mobiles = mobiles, templateId = templateId, params = params);
    var json = convert.jsonEncode(map);
    //print("============================$json");
    //{"addSerial":"106509712042733","apId":"lianji","mobiles":"15317068357","params":["123456"],"ecName":"浙江亮鲸网络科技有限公司","mac":"bc254cc28af2811b4ae1e919cf21e301","sign":"ngE5EvFes","templateId":"9fa2e2f1a84a4e10aa5f5d1b483755f0"}
    var baseData = toBase64Encode(json);
    //eyJhZGRTZXJpYWwiOiIxMDY1MDk3MTIwNDI3MzMiLCJhcElkIjoibGlhbmppIiwibW9iaWxlcyI6IjE1MzE3MDY4MzU3IiwicGFyYW1zIjpbIjEyMzQ1NiJdLCJlY05hbWUiOiLmtZnmsZ/kuq7psrjnvZHnu5znp
    //5HmioDmnInpmZDlhazlj7giLCJtYWMiOiJiYzI1NGNjMjhhZjI4MTFiNGFlMWU5MTljZjIxZTMwMSIsInNpZ24iOiJuZ0U1RXZGZXMiLCJ0ZW1wbGF0ZUlkIjoiOWZhMmUyZjFhODRhNGUxMGFhNWY1ZDFiNDgzNzU1ZjAifQ==
    //print("============================$baseData");
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        //print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // {"msgGroup":"0514082122000003648137","rspcod":"success","success":true}
        // {"msgGroup":"0514082249000004136511","rspcod":"success","success":true}
        print('成功:\n$result');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..contentType = ContentType.form //"application/json;charset=UTF-8"
      ..isEnableLog = AppDataConfig.isEnableLog
      ..data(baseData)
      ..postASync<SmsResult>(SmsResult())?.then((result) {
        print(result.toString());
        callback?.call(result);
      });
  }

  ///fixme 通过我们自己的服务器获取验证码
  ///mobiles 手机号
  static void getSmsCodeWithServer(BuildContext context, bool isEnableLoad,String mobiles,
      ResponseCallbackWithT<AppHttpResult<String?,String?>> callback) {
    if (StringUtils.isEmpty(mobiles)) {
      return;
    }
    var url = Url.baseurl() + Url.getcaptcha;
    var queryParameters = Map<String, dynamic>();
    var data = mobiles;
    var token = AppDataConfig.getToken();
    queryParameters['data'] = data;
    var sign = getSign(queryParameters);
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
    // ..onStart(() {
    //   print('开始');
    // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // {"Data":"838645","MsgCode":"100","MsgDetail":"短信发送成功"}
        // {"Data":"574621","MsgCode":"100","MsgDetail":"短信发送成功"}
        print('验证码请求获取成功:\n$result');
      })
    // ..onFinish(() {
    //   print('结束');
    // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormData('data', data)
      ..addFormData('sign', sign)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String?,String?>>(AppHttpResult()
        ..Data =""
        ..t2 = '')
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }
}
